from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView,RetrieveUpdateDestroyAPIView,CreateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from goods.models import Brand
from .serializer import *
from django.conf import settings
import os

from rest_framework.pagination import PageNumberPagination
# Create your views here.
# 分页器
class MyPagination(PageNumberPagination):
    page_size = 2
    page_query_param = 'page'
    page_size_query_param = 'pagesize'

# 品牌的视图集
class BrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSer
    # pagination_class = MyPagination
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 上传图片的视图类
class UploadBrandLogoView(APIView):
    def post(self,request):
        print('上传的图片数据',request.data,type(request.data))

        # 获取文件对象
        file = request.data.get('file')
        # file.file 上传的文件字节流对象
        # file.name 文件名字

        # 拼接路径
        static_path = 'static/images/logos'
        file_path = os.path.join(settings.BASE_DIR,static_path)
        file_name = os.path.join(file_path,file.name)

        # 保存图片
        with open(file_name,'wb')as f:
            f.write(file.file.read())

        # 返回响应
        data = {
            'code':200,
            'msg':'上传图片成功',
            'static_path':static_path
        }
        return Response(data)

# 加载所有的频道组数据
class ListChannelAPIView(ListAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer

# 加载所有的类别数据
class ListCateAPIView(ListAPIView):
    queryset = Cate.objects.all()
    serializer_class = CateSer

# 检索一个，修改一个，删除一个 频道组数据
class ChannelInfoAPIView(RetrieveUpdateDestroyAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 一级分类的视图
class FirstCateAPIView(ListAPIView):
    queryset = Cate.objects.filter(cid=None)
    serializer_class = CateSer

# 添加频道组
class AddChannelAPIView(CreateAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer

# SKU的数据集
class SKUViewSet(ModelViewSet):
    queryset = Good.objects.all()
    serializer_class = GoodSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# SPU的数据集
class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

# 加载子级类别
class SubCateAPIView(APIView):
    def get(self,request,pk):
        p_cate = Cate.objects.filter(id=pk).first()
        subs = p_cate.subs.all()
        ser = CateSer(subs,many=True)
        return Response(ser.data)

# 分页器
class SpecPagination(PageNumberPagination):
    page_size = 3
    max_page_size = 5
    page_query_param = 'page'
    page_size_query_param = 'pagesize'

# spu商品规格模型类
class SPUSpecView(ModelViewSet):
    queryset = SPUSpec.objects.all()
    serializer_class = SPUSpecSer
    pagination_class = SpecPagination
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'
#
#     def create(self, request, *args, **kwargs):
#         name = request.data.get('name')
#         spu_id = request.data.get('spu')
#         spusec = SPUSpec.objects.filter(spu=spu_id).first()
#         if spusec and spusec.spu.name == '华为P40':
#             SPUSpec.objects.create(name=name, spu_id=spu_id)
#             return Response({'msg':'添加成功'},status=201)
#         else:
#             return Response({'msg': '添加失败'}, status=404)
#
#     def destroy(self, request, *args, **kwargs):
#         spuspec = self.get_object()
#
#         if '小米' in spuspec.spu.name:
#             self.get_object().delete()
#             return Response({'msg': '删除成功'}, status=204)
#         else:
#             return Response({'msg': '删除失败'}, status=404)


# 规格选项值的视图
class SpecOptionViewSet(ModelViewSet):
    queryset = SpecOption.objects.all()
    serializer_class = SpecOptionSer
    pagination_class = SpecPagination
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    # def update(self, request, *args, **kwargs):
    #     value = request.data.get('value')
    #     spec = request.data.get('spec')
    #
    #     if value.find('\d', 0, -1):
    #         onespec = self.get_object()
    #         print('>>>>>>',onespec)
    #         onespec.value = value
    #         onespec.spec_id = spec
    #         onespec.save()
    #         return Response({'msg':'修改成功'})
    #     else:
    #         return Response({'msg':'只有数值可以修改'})
    #
    # def create(self, request, *args, **kwargs):
    #     value = request.data.get('value')
    #     spec_id = request.data.get('spec')
    #
    #     spec = SpecOption.objects.filter(value=value).first()
    #
    #     if spec:
    #         return Response({'msg':'该规格已存在,不可重复添加'})
    #     else:
    #         SpecOption.objects.create(value=value,spec_id=spec_id)
    #         return Response({'msg':'添加成功'})
    #
    # def destroy(self, request, *args, **kwargs):
    #     onespec = self.get_object()
    #     if ' 小米'in onespec.spec.spu.name:
    #         onespec.delete()
    #         return Response({'msg':'删除成功'})
    #     else:
    #         return Response({'msg':'删除失败'})


# 上传商品图片的接口
# ExpiredSignatureError捕获异常过期
# DecodeError口令验证
from rest_framework_jwt.utils import jwt_encode_handler
from jwt.exceptions import ExpiredSignatureError,DecodeError


class UploadSKUImageAPIView(APIView):
    def post(self,request):
        print('上传商品图片的请求',request.data)

        # 1.获取前端数据
        token = request.data.get('token')
        file = request.data.get('file')

        # 2.token的验证
        # try:
        #     payload = jwt_encode_handler(token)
        #
        # except ExpiredSignatureError:
        #     return Response({'code':401,'msg':'口令过期'})
        #
        # except DecodeError:
        #     return Response({'code': 401, 'msg': '口令不正确'})

        # 3.用户已登录，可以上传图片
        file_name = file.name
        static_path = 'static/image/goods'
        abs_path = os.path.join(settings.BASE_DIR,static_path)

        # 4.判断目录不存在时，创建出来
        if not os.path.exists(abs_path):
            os.makedirs(abs_path)

        # 5.写入图片
        sku_image_path = os.path.join(abs_path,file_name)

        with open(sku_image_path,'wb') as f:
            f.write(file.file.read())

        # 返回响应
        return Response({
            'code':200,
            'msg':'上传图片成功',
            'static_path':static_path,
            })


# 商品图片的视图
class SKUImageViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSer
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'

    def create(self, request, *args, **kwargs):
        # 1.获取前端数据
        sku_id = request.data.get('sku')
        image = request.data.get('image')

        # 2.判断该商品是否已添加图片
        results = SKUImage.objects.filter(sku_id=sku_id,image=image).first()

        if results:
            return Response({'code':400,'msg':'该商品已添加该图片'})
        else:
            try:
                SKUImage.objects.create(sku_id=sku_id,image=image)
                return Response({'msg': '图片添加成功'},status=201)
            except:
                return Response({'msg': '图片添加失败'})

    def update(self, request, *args, **kwargs):
        # 1.获取前端数据
        sku_id = request.data.get('sku')
        image = request.data.get('image')

        # 2.判断该商品是否已添加图片
        results = SKUImage.objects.filter(sku_id=sku_id,image=image).first()

        if results:
            return Response({'code': 400, 'msg': '该商品已添加该图片'})
        else:
            try:
                result = self.get_object()
                result.sku_id = sku_id
                result.image = image
                result.save()
                return Response({'msg': '图片修改成功'}, status=201)
            except:
                return Response({'msg': '图片修改失败'})


# 七牛云token的视图
from qiniu import Auth
ak = '9NycQ3LkdyQimfLzDJ-NpxE2xQHBy7GV2VEsHLIf'
sk = '5qsoP9JY-M7RGcLhM7Rpk1lKzFbYApJIxLIKzErp'

class QiniuTokenAPIVIew(APIView):
    def get(self,request):
        # 生成七牛云token
        token = self.get_token()

        # 返回响应
        return Response({'code':200,'token':token})

    @staticmethod
    def get_token():
        # 实例化鉴权对象
        q = Auth(ak,sk)

        # 生成token
        token = q.upload_token('shiluyao')

        return token


